import React, { useState, useEffect } from 'react';
import Topic from '../components/Topic';
import Post from '../components/Post';
import Participants from '../components/Participants';
import RadioButton from '../components/RadioButton';
import './Home.css'
import { useMatch } from 'react-router-dom';
import { searchTopicDetail,getParticipants} from '../api/userApi';

const TopicDetail = () => {
  const [userId, setUserId] = useState(null); // 新增 userId 状态
  const [category, setCategory] = useState('latest'); // 管理当前选择的排序类型
  // 处理排序方式的改变
  const handleCategoryChange = (newCategory) => {
    setCategory(newCategory); // 更新排序方式
  };

  const match = useMatch("/topic/:interestId");  
  const interestId = match ? match.params.interestId : null;   // 从 match 中获取 userId
  const [loading, setLoading] = useState(true);      // 加载状态
  const [error, setError] = useState(null);          // 错误状态
  const [TopicDetail, setTopicDetail] = useState([]);  // 初始化为空数组
  const [topic,setTopic]=useState([]);
  const [userBlogs,setUserBlogs]=useState([]);
  const [participants,setParticipants]=useState([]);

  useEffect(() => {
    const storedUserId = localStorage.getItem('userId');
    if (storedUserId) {
      setUserId(storedUserId);
    } else {
      console.log("User ID not available yet.");
    }
  }, []); // 只在组件挂载时执行一次

  // 发起 API 请求并处理数据
  useEffect(() => {
    if (!userId || !interestId) {
      console.log("Missing userId or interestId");
      return;
    }
    setLoading(true); // 请求开始时设置加载状态
    console.log("Making request with userId:", userId, "interestId:", interestId);
    searchTopicDetail(interestId, userId)
      .then((data) => {
        setTopicDetail(data);
        setTopic(data.interest);
        setUserBlogs(data.userBlogs);
        setLoading(false);
      })
      .catch((error) => {
        setError('Error fetching TopicDetail: ' + error.message);
        setLoading(false);
      });
  }, [userId, interestId]); 

  useEffect(() => {
    if ( !interestId) {
      console.log("Missing interestId");
      return;
    }
    setLoading(true); // 请求开始时设置加载状态
    console.log("interestId:", interestId);
    getParticipants(interestId)
      .then((data) => {
        setParticipants(data.data);
        setLoading(false);
      })
      .catch((error) => {
        setError('Error fetching TopicDetail: ' + error.message);
        setLoading(false);
      });
  }, [interestId]); 

  if (loading) {
    return <p>Loading...</p>;
  }

  if (error) {
    return <p>Error: {error}</p>;
  }

  const topicCard = (topic) => ({
    interestId: topic.interestId,  // 兴趣 ID
    title: topic.name,  
    description: topic.description,  // 兴趣描述
    image: topic.image,  // 兴趣图片
    updateTime: topic.updateTime,  // 更新时间
    count: topic.collectionCounts,  // 收藏数量
    isBookmarked: topic.isCollected,  // 是否已收藏（1为已收藏，0为未收藏）
  });

  const posts = userBlogs.map((blog) => ({
    userId: blog.userId,
    userImage: blog.userImage,
    blogImage: blog.blogImage,
    blogId: blog.blogId, // 确保使用正确的字段名称
    interestId: blog.interestId,
    title: blog.name,
    author: blog.account,
    content: blog.description,
    time: blog.updateTime,
    likeCount: blog.likesCount,
    commentCount: blog.commentsCount,
    isLiked: blog.isLiked,
    isFollowed: blog.isFollowed,
    isCollected: blog.isCollected,
  }));

  // 根据选择的排序方式处理帖子
  const sortedResults = () => {
    switch (category) {
      case 'latest':
        return posts.sort((a, b) => new Date(b.time) - new Date(a.time));
      case 'hotest':
        return posts.sort((a, b) => b.likeCount - a.likeCount);
      default:
        return posts;
    }
  };
  
  const renderPosts = () => {
    const sortedPosts = sortedResults();
    if (sortedPosts.length === 0) {
      return <p>没有找到相关帖子</p>;
    }
    return (
      <ul style={{ padding: "0" }}>
        {sortedPosts.map((post) => (
          <div key={post.blogId}>
            <Post post={post} />
          </div>
        ))}
      </ul>
    );
  };
  
  
  return (
    <div className="home">
      <div className="home-left">
        <div className="home-header">
          <Topic topic={topicCard(topic)} />
        </div>
        <div className="home-body" style={{ marginTop: '20px'}}>
          <RadioButton category={category} onCategoryChange={handleCategoryChange} />
          <div className="posts-section" style={{ marginTop: '10px'}}>
            {renderPosts()}
          </div>
        </div>
      </div>
      <div className="right-section">
        <Participants participants={participants}/>
      </div>
    </div>
  );
};

export default TopicDetail;
